/**
 * Copyright 2008 by Robert Konigsberg
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the same terms as Perl.
 *
 * @see http://www.perl.com/perl/misc/Artistic.html
 */
package visitor.edge;

import java.util.HashSet;
import java.util.Set;

import visitor.maze.Direction;
import visitor.maze.Maze;
import visitor.maze.Room;

public class Walker {
  private Set<Edge> visited = new HashSet<Edge>();
  private Room room;
  private Direction heading;

  public Walker(Maze maze, int start, Direction heading) {
    this.room = maze.getRoom(start);
    this.heading = heading;
  }

  public void walk(EdgeVisitor visitor) {
    while(true) {
      Edge edge = selectNextEdge(visitor, heading, room);
      if (edge == null) {
        return;
      }
      visited.add(edge);
      visitor.visit(edge);
      room = edge.getTo();
      heading = edge.getHeading();
    }
  }

  private Edge selectNextEdge(EdgeVisitor visitor, Direction direction, Room room) {
    Direction d = direction.left();
    for (int i = 0; i < 4; i++) {
      if (room.getExit(d) != null) {
        Edge edge = new Edge(room, d);
        if (!visited.contains(edge) && visitor.shouldVisit(edge)) {
          return edge;
        }
      }
      d = d.right();
    }
    return null;
  }
}
